﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.DbForms.ExecuteForms;
using DevelopTool.Forms.DbForms.FunctionForms;
using DevelopTool.Forms.DbForms.ProcedureForms;
using DevelopTool.Forms.DbForms.TriggerForms;
using DevelopTool.Forms.DbForms.ViewForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model;
using DevelopTool.Model.DbModels;
using Sunny.UI;

namespace DevelopTool.Forms.DbForms.ColumnForms
{
    public partial class OracleTableColumnForm : BaseUIPage
    {
        /// <summary>
        /// 连接信息
        /// </summary>
        private DbInfo dbInfo;

        /// <summary>
        /// Oracle操作类
        /// </summary>
        private OracleDbBll oracleDbBll;

        /// <summary>
        /// 查询条件
        /// </summary>
        private string queryKeyword;

        /// <summary>
        /// 查询实例
        /// </summary>
        private string queryDataBase;

        /// <summary>
        /// 查询资源名
        /// </summary>
        private string queryInfoName;

        /// <summary>
        /// 字段名
        /// </summary>
        private string queryColumnName;

        /// <summary>
        /// DataGridView列信息集合
        /// </summary>
        private List<DataGridColumn> dataGridColumns = new List<DataGridColumn>()
              {
                { new DataGridColumn("COLUMN_NAME"){ColumnText="字段名",Width=0,ColumnType=ColumnType.DefaultFilter}},
                { new DataGridColumn("COMMENTS"){ColumnText="注释",Width=0,ColumnType=ColumnType.DefaultFilter}},
                { new DataGridColumn("NUM_ROWS"){ColumnText="数据条数",Width=-1}},
                { new DataGridColumn("TABLE_NAME"){ColumnText="表名",Width=0}},
                { new DataGridColumn("OWNER"){ColumnText="实例",Width=100}},
                { new DataGridColumn("DATA_TYPE"){ColumnText="数据类型",Width=180}},
                { new DataGridColumn("DATA_DEFAULT"){ColumnText="默认值",Width=-1}},
                { new DataGridColumn("NULLABLE"){ColumnText="可为空",Width=-1}},
                { new DataGridColumn("DATA_LENGTH"){ColumnText="列长度",Width=-1}},
                { new DataGridColumn("DATA_PRECISION"){ColumnText="精度",Width=-1}},
                { new DataGridColumn("DATA_SCALE"){ColumnText="小数点精度",Width=-1}},
                { new DataGridColumn("COLUMN_ID"){ColumnText="序号",Width=-1}},
                 { new DataGridColumn("HIDDEN_COLUMN"){ColumnText="隐藏列",Width=100, ColumnType = ColumnType.Hide}},
                 { new DataGridColumn("VIRTUAL_COLUMN"){ColumnText="虚拟列",Width=100, ColumnType = ColumnType.Hide}}
              };


        public OracleTableColumnForm(DbInfo dbInfo)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
        }

        public OracleTableColumnForm(DbInfo dbInfo,string queryKeyword)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();

            this.queryKeyword = queryKeyword;
        }

        public OracleTableColumnForm(DbInfo dbInfo,string queryDataBase,string queryInfoName)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
            this.queryDataBase = queryDataBase;
            this.queryInfoName = queryInfoName;
        }

        public OracleTableColumnForm(DbInfo dbInfo,string queryDataBase,string queryInfoName,string queryColumnName)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
            this.queryDataBase = queryDataBase;
            this.queryInfoName = queryInfoName;
            this.queryColumnName = queryColumnName;
        }

        private void OracleColumnInfoForm_Load(object sender,EventArgs e)
        {
            this.oracleDbBll = new OracleDbBll(dbInfo);

            InitDate();

            this.dataDisplayControl.DbInfo = this.dbInfo;

            this.dataDisplayControl.BindContextMenuStrip(this.ContextMenuStripDgv);//绑定右键菜单
        }

        private void InitDate()
        {
            DataTable dataTable = new DataTable();
            LoadingHelper.ShowLoading("获取表字段",() =>
            {
                //查询字段信息
                dataTable = oracleDbBll.GetTableColumns(queryDataBase,queryInfoName,queryColumnName);
            });

            this.dataDisplayControl.BindData(dataTable,this.dataGridColumns,"COLUMN_ID ASC");

            if(!string.IsNullOrEmpty(queryKeyword)) this.dataDisplayControl.Search(queryKeyword);
        }


        #region 右键菜单事件

        private void 查询选定行ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            foreach(DataGridViewCell cell in this.dataDisplayControl.DataGridView.SelectedCells)
            {
                var row = this.dataDisplayControl.DataGridView.Rows[cell.RowIndex];//当前选中的行
                string column_name = row.Cells["COLUMN_NAME"].Value.ToString();//取得列名
                string table_Name = row.Cells["TABLE_NAME"].Value.ToString();//取得表名
                string dataBase_Name = row.Cells["OWNER"].Value.ToString();//取得实例名

                if(column_name.IsEmpty() || table_Name.IsEmpty() || dataBase_Name.IsEmpty())
                {
                    row.Cells["NUM_ROWS"].Value = string.Empty;
                    continue;
                }

                int rowCount = 0;
                LoadingHelper.ShowLoading($"获取字段{column_name}数据条数",() =>
                {
                    rowCount = oracleDbBll.GetColumnDateRowNum(dataBase_Name,table_Name,column_name);
                });
                row.Cells["NUM_ROWS"].Value = rowCount;
            }
        }


        private void 从当前行开始ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            DataGridViewCell currentCell = this.dataDisplayControl.DataGridView.SelectedCells[0];//当前选中的单元格

            LoadingHelper.ShowLoading($"从{currentCell.RowIndex}行开始获取数据条数",() =>
            {
                try
                {
                    for(int i = currentCell.RowIndex ; i < this.dataDisplayControl.DataGridView.Rows.Count ; i++)
                    {
                        var row = this.dataDisplayControl.DataGridView.Rows[i];
                        string column_name = row.Cells["COLUMN_NAME"].Value.ToString();//取得列名
                        string table_Name = row.Cells["TABLE_NAME"].Value.ToString();//取得表名
                        string dataBase_Name = row.Cells["OWNER"].Value.ToString();//取得实例名

                        if(column_name.IsEmpty() || table_Name.IsEmpty() || dataBase_Name.IsEmpty())
                        {
                            row.Cells["NUM_ROWS"].Value = string.Empty;
                            continue;
                        }
                        LoadingHelper.SetLoadingMsg($"获取字段{column_name}数据条数");

                        row.Cells["NUM_ROWS"].Value = oracleDbBll.GetColumnDateRowNum(dataBase_Name,table_Name,column_name);
                    }
                }
                catch(Exception ex)
                {
                    this.ShowWarningNotifier(ex.Message);
                }
            });

        }


        private void 在视图中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleViewForm(dbInfo,columnName),$"{dbInfo.NodeName}-视图",true,$"{columnName}-OracleViewForm");
            }
        }

        private void 在存储过程中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleProcedureForm(dbInfo,columnName),$"{dbInfo.NodeName}-存储过程",true,$"{columnName}-OracleProcedureForm");
            }
        }

        private void 在函数中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleFunctionForm(dbInfo,columnName),$"{dbInfo.NodeName}-函数",true,$"{columnName}-OracleFunctionForm");
            }
        }


        private void 在触发器中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleTriggerForm(dbInfo,columnName),$"{dbInfo.NodeName}-触发器",true,$"{columnName}-OracleTriggerForm");
            }
        }


        private void 查找同名字段ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
            this.dataDisplayControl.Search(columnName);
        }

        private void 查找同注释字段ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string comments = this.dataDisplayControl.SelectedRowDic["COMMENTS"];
            this.dataDisplayControl.Search(comments);
        }

        #endregion

        private void dataDisplayControl_DataReLoad(object sender,EventArgs e)
        {
            InitDate();
        }


        private void 查询数据_只查询本字段ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                string columnName = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];

                string sql = $"select {columnName} from {owner}.{tableName} where 1=1";
                TabControlHelper.AddPageToTabControl(parentTabControl,new ExecuteSqlForm(dbInfo,sql),$"{dbInfo.NodeName}-查询",true,$"{columnName}-ExecuteSqlForm");
            }
        }


        private void 查询数据_查询选中表ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];

                string sql = $"select * from {owner}.{tableName} where 1=1";
                TabControlHelper.AddPageToTabControl(parentTabControl,new ExecuteSqlForm(dbInfo,sql),$"{dbInfo.NodeName}-查询",true,$"{tableName}-ExecuteSqlForm");
            }
        }

        private void 添加到分组ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string dataBase = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string name = this.dataDisplayControl.SelectedRowDic["COLUMN_NAME"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];

            DbSourceGroupHelper.AddSourceToGroup(dataBase,name,"TResTableColumn",this.dbInfo,tableName);
        }

    }
}
